#include "my_call.h"

MyCall::~MyCall()
{

}

void MyCall::onCallState(OnCallStateParam &prm)
{
    CallInfo ci = getInfo();
    if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
        qDebug()<<"call is over.";
        emit EOnCallStateOver();
        /* Delete the call */
        delete this;
    }
}

void MyCall::onCallMediaState(OnCallMediaStateParam &prm)
{
    CallInfo ci = getInfo();

    for (unsigned i = 0; i < ci.media.size(); i++) {
        if (ci.media[i].type==PJMEDIA_TYPE_AUDIO) {
            try {
                //创建音频文件播放类并记录是否创建
                remoteWavPlayerS.player.createPlayer("/home/wuwei/PJSIP/pjsip_code/qtdemo/ring_1.wav");
                remoteWavPlayerS.isPlayerCreate = true;

                //获取远程的音频端口并记录
                AudioMedia remoteAudMed = getAudioMedia(i);
                remoteWavPlayerS.isDestinationAudMediaGet = true;
                remoteWavPlayerS.destinationAudMedia = remoteAudMed;

                //获取音频设备
                AudDevManager& mgr = Endpoint::instance().audDevManager();

                //双向传输
                remoteAudMed.startTransmit(mgr.getPlaybackDevMedia());
                mgr.getCaptureDevMedia().startTransmit(remoteAudMed);

                emit EOnCallMediaState();
            }
            catch(const Error &e) {
              // Handle invalid or not audio media error here
               qDebug()<<"MyCall::onCallMediaState *****************************";
               qDebug()<<"voice send error";
               qDebug()<<"******************************************************";
            }
        }
    }
}

void MyCall::onInstantMessage(OnInstantMessageParam &prm)
{
    // 处理接收到的即时消息
    qDebug()<<"Received Instant Message:" <<endl;
    std::cout << "From: " << prm.fromUri << std::endl;
    std::cout << "to: " << prm.toUri << std::endl;
    std::cout << "ContentType: " << prm.contentType << std::endl;
    iprmDefault = prm;

    emit EOnInstantMessage(&iprmDefault);
}

void MyCall::stopSendMusic(void)
{
    qDebug()<<"stop music going";
    if(remoteWavPlayerS.isDestinationAudMediaGet == true)
    {
        AudioMedia remoteAudMed = remoteWavPlayerS.destinationAudMedia;
        remoteWavPlayerS.player.stopTransmit(remoteAudMed);
    }
    else
    {
        qDebug()<<"You don't have DestinationAudMedia.";
    }
}

void MyCall::startSendMusic(void)
{
    qDebug()<<"start music going";
    if(remoteWavPlayerS.isDestinationAudMediaGet == true)
    {
        AudioMedia remoteAudMed = remoteWavPlayerS.destinationAudMedia;
        remoteWavPlayerS.player.startTransmit(remoteAudMed);
    }
    else
    {
        qDebug()<<"You don't have DestinationAudMedia.";
    }
}
